package com.example.fcm;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.messaging.FirebaseMessaging;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int NOTIFICATION_PERMISSION_REQUEST_CODE = 1001;
    private static final int MAX_RETRIES = 3;
    private int retryCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        onClickNotifications(); //点击通知

        // 初始化Firebase
        // FirebaseApp.initializeApp(this);

        // 请求通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        NOTIFICATION_PERMISSION_REQUEST_CODE);
            }
        }

        // 获取FCM token
        getFCMToken();

    }

    private void onClickNotifications() {
        Log.d(TAG, "onClickNotifications");
        Intent intent = getIntent();
        if (intent == null) {
            Log.d(TAG, "Intent is null");
            return;
        }
        TextView body_tv = findViewById(R.id.body);
        StringBuffer sb = new StringBuffer();

        Bundle data = intent.getBundleExtra("data");
        if (data != null) { //如果进程存活
            String line = "===========进程存活===========";
            Log.d(TAG, line);
            sb.append(line);
            sb.append("\n");
            for (String key : data.keySet()) {
                String msg = key + " = " + data.get(key).toString();
                Log.d(TAG, msg);
                sb.append(msg);
                sb.append("\n");
            }
        } else {
            // 打印所有 extra 数据
            Bundle extras = intent.getExtras();
            if (extras != null) { //如果进程存活
                String line = "==========进程被杀死============";
                Log.d(TAG, line);
                sb.append(line);
                sb.append("\n");
                for (String key : extras.keySet()) {
                    Object value = extras.get(key);
                    String msg = key + " = " + value.toString();
                    Log.d(TAG, msg);
                    sb.append(msg);
                    sb.append("\n");
                }
            } else { //如果进程被杀死
                String msg = "No extras found in intent";
                Log.d(TAG, msg);
                sb.append(msg);
                sb.append("\n");
            }

        }

        body_tv.setText(sb.toString());

    }

    private void getFCMToken() {
        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(new OnCompleteListener<String>() {
                    @Override
                    public void onComplete(Task<String> task) {
                        if (!task.isSuccessful()) {
                            Log.w(TAG, "Fetching FCM registration token failed", task.getException());

                            // 重试机制
                            if (retryCount < MAX_RETRIES) {
                                retryCount++;
                                Log.d(TAG, "Retrying to get token, attempt: " + retryCount);
                                try {
                                    Thread.sleep(2000); // 等待2秒后重试
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                getFCMToken();
                            } else {
                                Log.e(TAG, "Failed to get token after " + MAX_RETRIES + " attempts");
                            }
                            return;
                        }

                        // 获取新的token ,这里一定要科学上网,才能连接成功
                        String token = task.getResult();
                        Log.d(TAG, "FCM Token: " + token);
                    }
                });
    }
}